import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import PropTypes from 'react-router/lib/PropTypes'
import forEach from 'lodash/forEach'
import isEmpty from 'lodash/isEmpty'
import * as RepeatAction from '../actions/repeat'
import {WeaTable} from 'comsRedux'
import {
    WeaTop,
    WeaTab,
    WeaLeftTree,
    WeaLeftRightLayout,
    WeaSearchGroup,
    WeaRightMenu,
    WeaPopoverHrm,
    WeaDialog
} from 'ecCom'

import {WeaErrorPage,WeaTools} from 'ecCom'
import {Button,Form,Row,Col,Icon,DatePicker,Modal} from 'antd'
import Immutable from 'immutable'
const createForm = Form.create;
const FormItem = Form.Item;
const is = Immutable.is;
const WeaTableAction = WeaTable.action;
let _this = null;
const dialog=new Dialog();
import CreateMeeting from './createMeeting/index'
``
import PreviewMeeting from './previewmeeting/index'

class Repeat extends React.Component {
    static contextTypes = {
        router: PropTypes.routerShape
    }
    constructor(props) {
        super(props);
        _this = this;
        this.state = {
            showGroup: true,
        }
    }
    componentDidMount() {
        //一些初始化请求
        const { actions } = this.props;
        actions.initDatas();
        actions.doLoading();
    }
    componentWillReceiveProps(nextProps) {
    }
    
    componentWillUnmount() {
        //组件卸载时一般清理一些状态
    }
    
    render() {
        const {loading,title,actions,conditioninfo,showSearchAd,searchParamsAd,dataKey,topTab,advanceModal,advanceModalparams,createDate,controlModal,previewMeetingId} = this.props;
        const {showGroup} = this.state;
        const {getFieldProps} = this.props.form
        const buttons = [
            <Button key="save" type="primary" size="large" text="提 交" onClick={this.handleSubmit.bind(this,'advance')} >提 交</Button>
            ];
        const enddate = advanceModalparams['enddate'];

        return (
            <div className="metting-repeat" >
                
                    <WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
                        <WeaTop
                            title={title}
                            loading={loading}
                            icon={<i className='icon-search-search' />}
                            iconBgcolor='#55D2D4'
                            buttons={this.getButtons()}
                            buttonSpace={10}
                            showDropIcon={true}
                            dropMenuDatas={this.getRightMenu()}
                            onDropMenuClick={this.onRightMenuClick.bind(this)}
                        >
                            <WeaTab
                                buttonsAd={this.getTabButtonsAd()}//高级搜索底部按钮定义
                                searchsBaseValue={searchParamsAd.names}//快捷搜索对应字段
                                searchType={['base','advanced']}
                                setShowSearchAd={bool=>{actions.setShowSearchAd(bool)}}//高级搜索显示控制事件
                                hideSearchAd={()=> actions.setShowSearchAd(false)}//隐藏高级搜索
                                searchsAd={<Form horizontal>{this.getSearchs()}</Form>}//高级搜索表单内容
                                showSearchAd={showSearchAd}//是否显示高级搜索
                                onSearch={v=>{actions.doLoading(searchParamsAd)}}//快捷搜索按钮触发事件
                                selectedKey={searchParamsAd.timeSag?searchParamsAd.timeSag:0}
                                onSearchChange={v=>{actions.saveFields({names:{name:'names',value:v}})}}//快捷搜索内容变更触发事件
                                keyParam="viewcondition"  //主键
                                countParam="groupid" //数量
                                onChange={this.changeData.bind(this)}
                                datas={topTab}
                            
                            />
                            {
                                loading ? '加载中' :
                                <WeaTable
                                    sessionkey={dataKey}
                                    hasOrder={true}
                                    needScroll={false}
                                    onOperatesClick={this.getOperatesClick.bind(this)}//列表操作菜单
                                    getColumns = {this.getColumns}
                                />
                            }
                        </WeaTop>
                    </WeaRightMenu>
               <WeaDialog
                    visible={advanceModal}
                    title="提前结束重复会议"
                    icon="icon-coms-meeting"
                    iconBgcolor="#f14a2d"
                    buttons={buttons}
                    style={{width:'520px',height:'200px'}}
                    onCancel={()=>{actions.advanceModal(false)}}
                >
                    <div className="advance-over-body">
                        <Row className="wea-title" style={{borderBottom:'solid 1px #ebebeb',margin:'25px 25px 10px 25px'}}>
                            <Col span="20">
                                <div>修改日期</div>
                            </Col>
                            {
                                <Col span="4" style={{textAlign:"right",paddingRight:10,fontSize:12}}>
                                    <Icon type={showGroup ? 'up' : 'down'} onClick={()=>this.setState({showGroup:!showGroup})}/>
                                </Col>
                            }
                        </Row>
                        <Row className="wea-content" style={showGroup ? {} : {height:0,overflow:'hidden',padding:'0 25px'}}>
                            <Form horizontal>
                                <FormItem
                                labelCol= {{ span: 6 }}
                                wrapperCol= {{ span: 18 }}
                                label="重复结束日期"
                                style={{}}
                                >
                                    <DatePicker  style={{width:'150px'}} {...getFieldProps('enddate',{
                                        getValueFromEvent:(date, dateString) => dateString})} 
                                    disabledDate={this.disabledDate}
                                    defaultValue={enddate}
                                    />

                                </FormItem>
                            </Form>
                        </Row>
                        <Row>
                            <Col style={{paddingLeft:'28px',color:'#ff0000'}}>
                                <span>{`原定重复结束日期是[${enddate}],选择的日期只能小于该日期`}</span>
                            </Col>
                        </Row>
                    </div>

                    
                </WeaDialog>
                <PreviewMeeting 
                    meetingId = {previewMeetingId}
                    onClose={(meetingid='')=>{actions.savePreviewMeetingId({meetingid:meetingid})}}
                />
                <CreateMeeting
                    createType="isInterval"//周期会议isInterval，普通会议不用传
                    createDate={createDate}//默认当天，当天可不传，不要传空
                    visible={controlModal}//显示true/关闭false
                    onClose={(meetingid='')=>{actions.controlModal(false)}}//自定义的关闭组件方式，当点击X、草稿、提交按钮后抛出false,提交后会抛出meetingid
                 />

            </div>
        )
    }
    getColumns = (e)=>{
        const {actions} = this.props;
        let newColumns = '';
        newColumns = e.map(column => {
                let newColumn = column;
                newColumn.render = (text, record, index) => { //前端元素转义
                    let valueSpan = record[newColumn.dataIndex + "span"] !== undefined ? record[newColumn.dataIndex + "span"] : record[newColumn.dataIndex];
                    return(
                        newColumn.dataIndex == 'name'  ?
                         <div className="wea-url-name" style ={{cursor:'pointer'}} onClick={()=>{actions.savePreviewMeetingId({meetingid:record.id})}} dangerouslySetInnerHTML={{__html: valueSpan}} />
                        :
                         <div className="wea-url" dangerouslySetInnerHTML={{__html: valueSpan}} />

                    )
                }
                return newColumn;
            });
        return newColumns;
    }
    handleSubmit(type){
        const {actions,fields,advanceModalparams,searchParamsAd} = this.props;
        if(type == 'advance'){
            actions.StopIntvl({
                enddate:fields.enddate?fields.enddate.value:'',
                meetingid:advanceModalparams.meetingid,
            },{searchParamsAd})
            actions.advanceModal(false);

        }

    }
    disabledDate(current){
        const {advanceModalparams} = _this.props;
        const enddateString = advanceModalparams['enddate'];
        const enddate = new Date(enddateString);
        return current && current.getTime() > enddate.getTime();

    }
    
    onRightMenuClick(key){
        const {actions,searchParamsAd} = this.props;
        if(key == '0'){
            actions.doLoading(searchParamsAd);
            actions.setShowSearchAd(false);
        }else if(key == '1'){
            actions.doLoading();
            actions.setShowSearchAd(false);
        }
        
    }
    
    getRightMenu(){
        let btns = [];
        btns.push({
            icon: <i className='icon-Right-menu--search'/>,
            content:'搜索'
        });
        btns.push({
            icon: <i className='icon-Right-menu-Custom'/>,
            content:'重置'
        })
        return btns
    }
    getSearchs() {
        return [
            (<WeaSearchGroup needTigger={true}  title={this.getTitle()} showGroup={this.isShowFields()} items={this.getFields()}/>),
            (<WeaSearchGroup needTigger={true}  title={this.getTitle(1)} showGroup={this.isShowFields(1)} items={this.getFields(1)}/>)
        ]
    }
    getTitle(index = 0) {
        const {conditioninfo} = this.props;
        return !isEmpty(conditioninfo) && conditioninfo[index].title
    }
    isShowFields(index = 0) {
        const {conditioninfo} = this.props;
        if(conditioninfo.length==0){
            return true;
        }
        return !isEmpty(conditioninfo) && conditioninfo[index].defaultshow 
    }
    // 0 常用条件，1 其他条件
    getFields(index = 0) {
        const {conditioninfo} = this.props;
        const fieldsData = !isEmpty(conditioninfo) && conditioninfo[index].items;
        let items = [];
        forEach(fieldsData, (field) => {
            items.push({
                com:(<FormItem
                    label={`${field.label}`}
                    labelCol={{span: `${field.labelcol}`}}
                    wrapperCol={{span: `${field.fieldcol}`}}>
                    {WeaTools.switchComponent(this.props, field.key, field.domkey, field)}
                </FormItem>),
                colSpan:1
            })
        })
        return items;
    }
    
    getTabButtonsAd() {
        const {actions,searchParamsAd} = this.props;
        return [
            (<Button type="primary" onClick={()=>{actions.doLoading(searchParamsAd);actions.setShowSearchAd(false)}}>搜索</Button>),
            (<Button type="ghost" onClick={()=>{actions.saveFields({})}}>重置</Button>),
            (<Button type="ghost" onClick={()=>{actions.setShowSearchAd(false)}}>取消</Button>)
        ]
    }
    
    getButtons() {
        const { dataKey, comsWeaTable, actions,searchParamsAd} = this.props;
        const tablekey = dataKey ? dataKey.split('_')[0] : 'init';
        const tableNow = comsWeaTable.get(tablekey);
        const selectedRowKeys = tableNow.get('selectedRowKeys');
        let btns = [];
        btns.push(<Button type="primary" onClick={()=>{actions.controlModal(true,new Date())}}>新建</Button>)
        btns.push(<Button type="ghost" disabled={!(selectedRowKeys)}
                          onClick={()=>{
                              if(`${selectedRowKeys.toJS()}`==""){
                                    alert("您没指定要删除的会议！");
                                }else{
                                    Modal.confirm({
                                        content: '确定要删除已选择的会议吗？',
                                        onOk() {
                                            actions.DeleteIntvl({meetingid:`${selectedRowKeys.toJS()}`});
                                            actions.doLoading(searchParamsAd);
                                        }
                                    });
                                    
                                } 
                                      }}>删除</Button>)
        return btns
    }
    //标签页切换时触发
    changeData(theKey) {
        let {actions,searchParamsAd,fields} = this.props;
        searchParamsAd.timeSag = theKey;
        actions.saveFields({...fields,timeSag:{name:'timeSag',value:theKey}});
        actions.setShowSearchAd(false);
        searchParamsAd.topTab = undefined;
        actions.doLoading(searchParamsAd);
    }
    
	//列表后操作菜单
	getOperatesClick(record,index,operate,flag){
		const {actions,searchParamsAd} = this.props;
		let meetingid=record.id;
		let operateType=operate.index;//根据后台接口操作按钮显示顺序确定操作类型 0停止 1提前结束 2取消
		if(operateType==0){
			actions.StopIntvl({meetingid},{searchParamsAd});
			//actions.doLoading(searchParamsAd);
		}else if(operateType==1){
            actions.saveFields({enddate:{name:'enddate',value:record.repeatenddate}});
            actions.advanceModal(true,{
                meetingid:meetingid,
                enddate:record.repeatenddate,
            });
           
		}else if(operateType==2){
            Modal.confirm({
                content: '确定要取消该周期会议吗？',
                onOk() {
                    actions.CancelIntvl({meetingid});
                    actions.doLoading(searchParamsAd);
                }
            });
			
		}
	}
}

//组件检错机制
class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
        return(
            <WeaErrorPage msg={ hasErrorMsg ? this.props.error : "对不起，该页面异常，请联系管理员！" } />
        );
    }
}

let RepeatForm = WeaTools.tryCatch( React, MyErrorHandler, { error: "" })(Repeat);

//form 表单与 redux 双向绑定
RepeatForm = createForm(
    {
        onFieldsChange(props, fields) {
            props.actions.saveFields({ ...props.fields, ...fields });
        },
        mapPropsToFields(props) {
            return props.fields;
        }
    }
)(Repeat);


// 把 state map 到组件的 props 上
const mapStateToProps = state => {
    const { comsWeaTable} = state;
    return {...state.meetingRepeat,comsWeaTable}
}

// 把 dispatch map 到组件的 props 上
const mapDispatchToProps = dispatch => {
    return {
        actions: bindActionCreators({...RepeatAction,...WeaTableAction}, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(RepeatForm);